<?php
	/**
	 * 上课邮件通知
	 */
	defined('IN_PHPCMS') or exit('No permission resources.'); 
	$course_db = pc_base::load_model('courses_model');
	$member_db = pc_base::load_model('member_model');
	pc_base::load_sys_func('mail');
	
	//增加弹窗通知
	$phpcms_auth = param::get_cookie('auth');//用户登录判断
	$ct_notice_time = intval(param::get_cookie('ct_notice_time'));//最后一次通知时间
	$wait_time = 2*3600;
	$course_time_msg = array();
	if($phpcms_auth && ($ct_notice_time<1 || (SYS_TIME - $wait_time > $ct_notice_time))) {
		//$auth_key = md5(pc_base::load_config('system', 'auth_key').str_replace('7.0' ,'8.0',$_SERVER['HTTP_USER_AGENT']));
		$auth_key = md5(pc_base::load_config('system', 'auth_key').$_SERVER['HTTP_USER_AGENT']);
		list($userid, $password) = explode("\t", sys_auth($phpcms_auth, 'DECODE', $auth_key));
		//如果用户ID大于0
		if($userid >0) {
			//获得会员模型
			$member_modelid = get_memberinfo($userid, 'modelid');
			//根据会员模型来获取即将上课的课程，3天内的；如果模型是家长，获取绑定的课程
			// 10  我是学生   11  我是老师     12   我是家长
			$notice_userid = array();
			if ($member_modelid == 12)
			{
				$member_db->set_bind_model(true);
				$students = $member_db->select(array('parent_uid' => $userid, 'status' => 4));
				if ($students)
				{
					foreach ($students as $student)
					{
						$student_id = intval($student['student_uid']);
						if ($student_id<1) continue;
						if (@in_array($student_id, $notice_userid)) continue;
						$notice_userid[] = $student_id;
					}
				}
				$member_db->set_bind_model();
			}
			else 
			{
				$notice_userid[] = $userid;
			}
			//如果可用的通知ID大于0 ，实现通知
			if ($notice_userid)
			{
				//获得课程的绑定数据
				$courses = array();
				if ($member_modelid == 11)
				{
					$course_db->set_model(3);
					$sql_in = implode(',', $notice_userid);
					$rs = $course_db->query("SELECT DISTINCT course_time_id FROM {$course_db->table_name} WHERE teacher_id IN ({$sql_in}) AND is_allow=1 ");
					$result = $course_db->fetch_array();
					$course_db->set_model();
				}
				else 
				{
					$course_db->set_model(4);
					$sql_in = implode(',', $notice_userid);
					$rs = $course_db->query("SELECT DISTINCT course_time_id FROM {$course_db->table_name} WHERE student_id IN ({$sql_in}) AND is_allow=1 ");
					$result = $course_db->fetch_array();
					$course_db->set_model();
				}
				if ($result)
				{
					foreach ($result as $row)
					{
						$courses[] = $row['course_time_id'];
					}
				}
				//获取可用于通知的课程列表
				if ($courses)
				{
					$sql_in_course = implode(',', $courses);
					$time = SYS_TIME;
					$ct_rs = $course_db->query("SELECT ctid FROM {$course_db->table_name} WHERE ctid IN ({$sql_in_course}) AND ctime>=$time ORDER BY ctime DESC LIMIT 0, 5");
					$ct_result = $course_db->fetch_array();
					//格式化数据
					if ($ct_result)
					{
						foreach ($ct_result as $ct_key=>$ct_val)
						{
							$course_time_msg[$ct_val[ctid]] = get_special_course_time($ct_val['ctid']);
						}
					}
				}
			}//可通知用户结束
		}
	}
	if ($course_time_msg)
	{
		$html = "<div style='width:300px;border:1px solid #CCC;z-index:555;right:20px;".
				"bottom:20px;position:fixed;background-color:#acf4c0;'>";
		$html .= "<span style='background-color:#cbeeea;display:block;clear:both;".
				"margin-bottom:5px;color:#F00;font-weight:bold;text-align:center;".
				"height:24px; line-height:24px;'>课程通知".
				"<em style='font-style:normal;float:right;padding:0 6px;".
					"background-color:#F00;color:#FFF;cursor:pointer;display:inline-block;'".
					" onclick='javascript:this.parentNode.parentNode.style.display=\\\"none\\\";'>X</em>".
				"</span>";
		$html .= "<ul style='padding:3px 10px;'>";
		foreach ($course_time_msg as $ct)
		{
			$html .= "<li>{$ct['course_class_name']} [" .date("Y-m-d H:i:s", $ct['ctime'])."]</li>";
		}
		$html .= "</ul>";
		$html .= "<div style='clear:both; height:1px;'>&nbsp;</div></div>";
		//echo $html;
		echo("document.write(\"{$html}\");");
		//param::set_cookie('ct_notice_time', SYS_TIME + 4*3600);
	}
	//弹窗通知结束
die;

	//获得可通知的课程信息
	$course_infos = get_enable_course_time(7);
	
	//获得已通知的课程列表，此处不细分学生还是教师
	//数据结构：array(ctid=>array(uid,uid,uid...), ...);
	$cache_name = 'course_time_notice';
	$noticed_data = getcache($cache_name, 'commons');
	
	$notice_data_new = array();	//保存新的通知数据
	
	$notice_subject = "[%s] 上课通知";
	$notice_message = "亲爱的 %s %s ：<br />    您选择的课程 [%s] 将于 %s 上课，请您".
			"提前到达，不要迟到、不要错过。<br />   二中网校  <br />   %s ";
	
	//如果存在课程，则准备通知
	if ($course_infos)
	{
		foreach ($course_infos as $ckey=>$cval)
		{
			//如果没有缓存数据或者课程上不在缓存数据里面，则加入到新的通知数据里面，否则平移
			if (empty($noticed_data) || @!array_key_exists($cval['ctid'], $noticed_data))
			{
				$notice_data_new[$cval['ctid']] = array();
			}
			else 
			{
				$notice_data_new[$cval['ctid']] = $noticed_data[$cval['ctid']];
			}
			
			//获取学生的课程安排信息
			$course_db->set_model(4);
			$student_data = $course_db->select(array('course_time_id'=>"{$cval['ctid']}"), 'student_id');
			if ($student_data)
			{
				foreach ($student_data as $skey=>$sval)
				{
					if (@in_array($sval['student_id'], $notice_data_new[$cval['ctid']])) continue;
					//获得该会员的E-mail
					$member_data = $member_db->get_one(array('userid' => "{$sval['student_id']}"), 'username, email');
					$mail_subject = sprintf($notice_subject, $cval['course_inter_name']);
					$mail_content = sprintf($notice_message, $member_data['username'], '同学', $cval['course_inter_name'], date("Y-m-d H:i:s", $cval['ctime']),date("Y-m-d H:i:s", SYS_TIME));
					//开始发送邮件
					$mail_result = sendmail($member_data['email'], $mail_subject, $mail_content);
					//$mail_result = true;
					if ($mail_result == true)
					{
						$notice_data_new[$cval['ctid']][] = $sval['student_id'];
					}
				}
			}
			
			//获得教师的课程安排
			$course_db->set_model(3);
			$teacher_data = $course_db->select(array('course_time_id'=>"{$cval['ctid']}"), 'teacher_id');
			if ($teacher_data)
			{
				foreach ($teacher_data as $tkey=>$tval)
				{
					if (@in_array($tval['teacher_id'], $notice_data_new[$cval['ctid']])) continue;
					//获得该会员的E-mail
					$member_data = $member_db->get_one(array('userid' => "{$tval['teacher_id']}"), 'username, email');
					$mail_subject = sprintf($notice_subject, $cval['course_inter_name']);
					$mail_content = sprintf($notice_message, $member_data['username'], '老师', $cval['course_inter_name'], date("Y-m-d H:i:s", $cval['ctime']),date("Y-m-d H:i:s", SYS_TIME));
					//开始发送邮件
					$mail_result = sendmail($member_data['email'], $mail_subject, $mail_content);
					//$mail_result = true;
					if ($mail_result == true)
					{
						$notice_data_new[$cval['ctid']][] = $tval['teacher_id'];
					}
				}
			}
		}
	}
	//print_r($notice_data_new);
	
	//缓存保存
	setcache($cache_name, $notice_data_new, 'commons');
	
	/**
	 * 获得指定课时的相关信息
	 */
	function get_special_course_time($ctid)
	{
		global $course_db;
		$siteid = get_siteid();
		//获得可用的班级列表
		$classes = get_available_classes($siteid);
		//获得可用的课程列表
		$courses = get_available_courses($siteid);
		$course_db->set_model(0);
		$return = $course_db->get_one(array('ctid' => $ctid));
		if ($return)
		{
			$return['class_name'] = $classes[$return['cid']];
			$return['course_name'] = $courses[$return['csid']];
			$return['course_class_name'] = $return['class_name'].'  '.$return['course_name'];
		}
		$course_db->set_model();
		return $return;
	}
	
	/**
	 * 获得可用的课时信息
	 */
	function get_enable_course_time($days = 0)//该参数设置为获得几天以内的课程并通知，0为所有课程
	{
		global $course_db;
		$return = array();
		$course_db->set_model(0);
		$nowTime = SYS_TIME;
		$add_sql = '';
		if ($days>0)
		{
			$end_time = $nowTime + $days*24*3600;
			$add_sql = " AND ctime<'$end_time' ";
		}
		$siteid = get_siteid();
		$where = " siteid='$siteid' AND ctused='1' AND ctime>'$nowTime' $add_sql ";
		$return = $course_db->select($where);
		if ($return)
		{
			//获得可用的班级列表
			$classes = get_available_classes($siteid);
			//获得可用的课程列表
			$courses = get_available_courses($siteid);
			
			foreach ($return as $key=>$val)
			{
				//如果课程或者班级不在可用列表里面，不显示
				if (!@array_key_exists($val['csid'], $courses) || !@array_key_exists($val['cid'], $classes))
				{
					continue;
				}
				$return[$key]['course_inter_name'] = $classes[$val['cid']].'  '.$courses[$val['csid']];
			}
		}
		$course_db->set_model();
		return $return;
	}
	
	/**
	 * 获得可用的课程
	 */
	function get_available_courses($siteid, $all = false)//$all 为真时，忽略是否可用的条件
	{
		global $course_db;
		$return = array();
		$course_db->set_model(2);
		$sql_param = $all ? array('siteid'=>$siteid) : array('siteid'=>$siteid, 'csused'=>"1") ;
		$query = $course_db->select($sql_param);
		if ($query)
		{
			foreach ($query as $key=>$val)
			{
				$return[$val['csid']] = $val['csname'];
			}
		}
		$course_db->set_model();
		return $return;
	}	

	/**
	 * 获得可用的班级列表
	 */
	function get_available_classes($siteid, $all = false)
	{
		global $course_db;
		$return = array();
		$course_db->set_model(1);
		$sql_param = $all ? array('siteid'=>$siteid) : array('siteid'=>$siteid, 'cused'=>"1") ;
		$query = $course_db->select($sql_param);
		if ($query)
		{
			foreach ($query as $key=>$val)
			{
				$return[$val['cid']] = $val['cname'];
			}
		}
		$course_db->set_model();
		return $return;
	}

?>